package com.test.learnaidlclient.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.test.learnaidl.PersonInterface;
import com.test.learnaidlclient.R;
import com.test.learnaidlclient.utils.ToastUtils;


/*
    AIDL-修饰符in,out,inout
    https://www.yuque.com/jiajun-faizt/haag2g/atiecz

    安卓开发学习之AIDL的使用 https://blog.csdn.net/qq_37475168/article/details/80580773   此篇文章 代码里的注解比较详细

    android进阶-AIDL的基本使用  https://www.jianshu.com/p/5043a1a69269

    Android AIDL使用介绍（1）基本使用 https://blog.csdn.net/lansoul1987/article/details/104350185

    Android AIDL 使用 https://blog.51cto.com/u_15127640/2754027

     服务端工程：LearnAIDL

 */
public class PersonServiceActivity extends AppCompatActivity {
    EditText et_name;
    TextView tv_bind;
    TextView tv_set;
    TextView tv_get;
    private PersonInterface mPersonInterface;
    private boolean mBindServiceSuccess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        et_name = findViewById(R.id.et_name);
        tv_bind = findViewById(R.id.tv_bind);
        tv_set = findViewById(R.id.tv_set);
        tv_get = findViewById(R.id.tv_get);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    private void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        initEvent();
    }

    private void initEvent() {
        tv_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindServiceSuccess) {
                    bindPersonService();
                } else {
                    ToastUtils.show("不能重复绑定");

                    Log.i("==", "绑定 mBindServiceSuccess = " + mBindServiceSuccess + " 不能重复绑定");
                }

            }
        });

        tv_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setName();
            }
        });

        tv_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getName();
            }
        });
    }

    private void getName() {
        if (mPersonInterface == null) {
            Log.i("==", "请先绑定");
            ToastUtils.show("请先绑定");
            return;
        }

        String name = null;
        try {
            name = mPersonInterface.getName();
            ToastUtils.show("获取到的名字是：" + name);
        } catch (RemoteException e) {
            e.printStackTrace();//这里异常可能是服务端进程被杀死了，或者重新启动了
            mBindServiceSuccess = false;
            ToastUtils.show("获取到的名字异常,请重新绑定");
            Log.i("==", "获取到的名字异常 e: " + e.toString());
        }

    }

    private void setName() {
        if (mPersonInterface == null) {
            Log.i("==", "请先绑定");
            ToastUtils.show("请先绑定");
            return;
        }

        if (TextUtils.isEmpty(et_name.getText())) {
            ToastUtils.show("输入名字");
            return;
        }

        try {
            mPersonInterface.setName(et_name.getText().toString());
        } catch (RemoteException e) {
            e.printStackTrace();//这里异常可能是服务端进程被杀死了，或者重新启动了
            mBindServiceSuccess = false;
            ToastUtils.show("设置名字发生异常,请重新绑定");
            Log.i("==", "设置名字发生异常 e: " + e.toString());

        }

    }

    /**
     * 注意:PersonService需要先在清单文件里声明，不然会绑定失败
     */
    private void bindPersonService() {
        Intent intent = new Intent();
        intent.setAction("com.test.learnaidl.aidlservice");//服务端清单文件里配置的
        intent.setPackage("com.test.learnaidl");  // 注意在 Android 5.0以后，不能通过隐式 Intent 启动 service，必须制定包名
        mBindServiceSuccess = bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
        Log.i("==", "绑定 mBindServiceSuccess = " + mBindServiceSuccess);
        if (mBindServiceSuccess) {
            ToastUtils.show("绑定成功！");
        } else {
            ToastUtils.show("绑定失败！");
        }
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("==", "绑定 onServiceConnected 已连接 ");

            mPersonInterface = PersonInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("==", "绑定 onServiceDisconnected 已断开");


        }
    };

    @Override
    protected void onDestroy() {
        if (mBindServiceSuccess) {
            unbindService(mServiceConnection);
            mBindServiceSuccess = false;
            Log.i("==", "onDestroy unbindService 解绑 mServiceConnection");
        } else {
            Log.i("==", "onDestroy 绑定 mBindServiceSuccess =  " + mBindServiceSuccess + "无需解绑");
        }
        super.onDestroy();
    }
}